/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: WebViewFragment.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.web;


import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ClientCertRequest;
import android.webkit.HttpAuthHandler;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.ProgressBar;

import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cc.shinichi.library.ImagePreview;
import cc.shinichi.library.bean.ImageInfo;
import io.bhex.app.R;
import io.bhex.app.ScreenShot.BitmapUtils;
import io.bhex.app.app.BHexApplication;
import io.bhex.app.base.BaseFragment;
import io.bhex.app.main.ui.MainActivity;
import io.bhex.app.share.SHARE_MEDIA;
import io.bhex.app.share.ShareUtils;
import io.bhex.app.share.SystemShareUtils;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.DialogUtils;
import io.bhex.app.utils.FileTools;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.view.TopBar;
import io.bhex.app.web.bean.WebJsTradeBean;
import io.bhex.app.web.js.JsCallNative;
import io.bhex.app.web.presenter.WebJsBean;
import io.bhex.app.web.presenter.WebViewFragmentPresenter;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.constant.Fields;
import io.bhex.baselib.core.CApplication;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.Utils.CookieUtils;
import io.bhex.baselib.network.cookie.persistentcookiejar.persistence.SharedPrefsCookiePersistor;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.DevicesUtil;
import io.bhex.baselib.utils.ImageUtils;
import io.bhex.baselib.utils.PixelUtils;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.baselib.utils.crop.ImgPickHandler;
import io.bhex.baselib.utils.crop.ImgPickHelper;
import io.bhex.baselib.view.alertview.AlertView;
import io.bhex.baselib.view.alertview.OnDismissListener;
import io.bhex.baselib.view.alertview.OnItemClickListener;
import io.bhex.sdk.UrlsConfig;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.config.domain.BackupDomainManager;
import io.bhex.sdk.data_manager.RateAndLocalManager;
import io.bhex.sdk.data_manager.SymbolDataManager;
import io.bhex.sdk.quote.bean.CoinPairBean;
import io.bhex.sdk.socket.Base64;
import io.bhex.sdk.utils.UtilsApi;
import io.bhex.sdk.utils.bean.UploadImgResponse;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cookie;
import pub.devrel.easypermissions.EasyPermissions;
import zendesk.commonui.UiConfig;
import zendesk.support.guide.HelpCenterActivity;

import static android.app.Activity.RESULT_OK;

public class WebViewFragment extends BaseFragment<WebViewFragmentPresenter, WebViewFragmentPresenter.WebViewFragmentUI> implements WebViewFragmentPresenter.WebViewFragmentUI , EasyPermissions.PermissionCallbacks{

    public final static String KEY_URL = "url";
    public final static String TITLE = "title";
    public final static String MAINFRAGMENT = "bMainFragment";
    private WebView webView;
    private ProgressBar pb;
    private TopBar topBar;
    private boolean isSettedTitle;
    private View ll_network_error;
    private ValueCallback<Uri> mUploadMsg;
    private ValueCallback<Uri[]> mUploadFilesMsg;
    private boolean bMainFragment = false;
    private String mUrl;
    private String mNewUrl;
    private boolean mBnetworkError;
    private WVJBWebViewClient.WVJBResponseCallback mJSImageCallback;

    private static final int CAMERA_PERMISSION_REQUEST_CODE = 0x1;
    private static final int WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 0x2;
    private static final int WRITE_EXTERNAL_STORAGE_SHARE_PERMISSION_REQUEST_CODE = 0x3;
    private String[] selectPhotoWayArray;

    private MyWebViewClient myViewClient;
    public static final int LOGIN_RESULTCODE = 100;
    private static final int FILECHOOSER_RESULTCODE = 1000;
    private static final int REQ_CODE_FROM_CAMERA = 1001;
    private static final String[] INCLUDE_SCHEME_ARRAY = {
            "http", "https", WVJBWebViewClient.kCustomProtocolScheme
    };


    @Override
    protected WebViewFragmentPresenter.WebViewFragmentUI getUI() {
        return this;
    }

    @Override
    protected WebViewFragmentPresenter createPresenter() {
        return new WebViewFragmentPresenter();
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.web_layout, null, false);
    }

    @Override
    protected void initViews() {
        super.initViews();

        Bundle bundle = getArguments();
        if (bundle == null)
            return;
        String url = bundle.getString(KEY_URL);

        try {
            String currentH5Host = new URL(UrlsConfig.API_H5_URL).getHost();
            String host = new URL(url).getHost();
            if (BackupDomainManager.getInstance().isInOurDomains(host)) {
                if  (!host.equals(currentH5Host)) {
                    url = url.replaceFirst(host,currentH5Host);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        mUrl = url;
        String title = bundle.getString(TITLE);
        bMainFragment = bundle.getBoolean(MAINFRAGMENT);
        topBar = viewFinder.find(R.id.topBar);
        this.setTopbarNight(topBar);
        webView = viewFinder.find(R.id.webView);
        ll_network_error = viewFinder.find(R.id.ll_network_error);
        ll_network_error.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadUrl(webView.getUrl());
            }
        });
        selectPhotoWayArray = new String[]{getString(R.string.string_take_photo), getString(R.string.string_gallery)};
        pb = viewFinder.find(R.id.pb);
        if (bMainFragment == false) {
            topBar.setLeftText(getString(R.string.string_close_page));
            topBar.findViewById(R.id.title_bar_left_text).setVisibility(View.GONE);
            topBar.findViewById(R.id.title_bar_left_text).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (bMainFragment == false){
                        getActivity().finish();
                    }
                }
            });
        }

        topBar.findViewById(R.id.title_bar_left_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (webView.canGoBack()) {
                    GoBack(); // 返回前一个页面
                } else {
                    if (bMainFragment == false){
                        getActivity().finish();
                    }
                    //else
                    //loadUrl();

                }
            }
        });
        if (bMainFragment == true) {

            viewFinder.find(R.id.myStatusBar).setVisibility(View.VISIBLE);
            topBar.findViewById(R.id.title_bar_right_image).setVisibility(View.VISIBLE);
            ((ImageView) topBar.findViewById(R.id.title_bar_right_image)).setImageResource(R.mipmap.icon_fresh);
            ViewGroup.LayoutParams para;
            para = topBar.findViewById(R.id.title_bar_right_image).getLayoutParams();
            para.height = PixelUtils.dp2px(40);
            para.width = PixelUtils.dp2px(40);
            topBar.findViewById(R.id.title_bar_right_image).setLayoutParams(para);
            topBar.findViewById(R.id.title_bar_right_image).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    loadUrl(webView.getUrl());

                    //showSelectPhoto();
                }
            });
            topBar.findViewById(R.id.title_bar_left_img).setVisibility(View.GONE);
            //startTimer();
        }
        if (!TextUtils.isEmpty(title)) {
            topBar.setTitle(title);
            isSettedTitle = true;
        } else {
            isSettedTitle = false;
        }

        pb.setMax(100);

        initWebView();

        myViewClient = new MyWebViewClient(webView);
        webView.setWebViewClient(myViewClient);
        loadUrl(mUrl);
        //  刷新
        SmartRefreshLayout refreshLayout = viewFinder.find(R.id.refreshLayout);
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                loadUrl(webView.getUrl());
                refreshlayout.finishRefresh(1000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                refreshlayout.finishLoadMore(1000/*,false*/);//传入false表示加载失败
            }
        });
    }

    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    if (webView != null) {
                        if (webView.canGoBack()) {
                            showSecondPage(true);
                        } else {
                            showFirstPage();
                        }
                    }
                    break;
            }
            super.handleMessage(msg);
        }

    };


    public boolean GoBack() {
        if (webView != null && webView.canGoBack()) {
            webView.goBack();// 返回前一个页面
            int pageSize = webView.copyBackForwardList().getCurrentIndex();
            if (pageSize <= 1 && bMainFragment == true) {
                showFirstPage();
            }
            return true;
        }
        return false;

    }

    private void showFirstPage() {
        //((ImageView) topBar.findViewById(R.id.title_bar_left_img)).setImageResource(R.mipmap.icon_fresh);
        topBar.findViewById(R.id.title_bar_left_img).setVisibility(View.GONE);
        topBar.findViewById(R.id.title_bar_right_image).setVisibility(View.VISIBLE);
        if (mShowMainTabListener != null) {
            mShowMainTabListener.onShowMaintab(true);
        }

    }

    private void showSecondPage(boolean bBack) {
        topBar.findViewById(R.id.title_bar_left_img).setVisibility(View.VISIBLE);
        topBar.findViewById(R.id.title_bar_right_image).setVisibility(View.INVISIBLE);
        if (mShowMainTabListener != null) {
            if(bBack)
                mShowMainTabListener.onShowMaintab(false);
            else
                mShowMainTabListener.onShowMaintab(true);
        }
    }

    /**
     * 选择图片
     */
    private void showSelectPhoto(final boolean bWebViewFile) {
        AlertView selectPhotoAlert = new AlertView(null, null, getString(R.string.string_cancel), null, selectPhotoWayArray, getActivity(), AlertView.Style.ActionSheet, new OnItemClickListener() {
            @Override
            public void onItemClick(Object o, int position) {
                if (position == -1) {
                    if (mJSImageCallback != null) {

                        WebJsBean bean = new WebJsBean();
                        bean.code = "CANCEL";
                        Gson gson = new Gson();
                        String sendData = gson.toJson(bean);
                        mJSImageCallback.callback(sendData);
                    }
                    return;
                }
                if (position == 0) {
                    //拍照
                    startSelectImage(true, bWebViewFile);

                } else {
                    //从相册选择
                    startSelectImage(false, bWebViewFile);
                }
            }
        });
        selectPhotoAlert.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(Object o) {

            }
        });
        selectPhotoAlert.show();
    }

    private void startSelectImage(boolean bCamera, final boolean bWebViewFile) {

        ImgPickHelper.getInstance().registeHandler(new ImgPickHandler() {

            @Override
            public void onSuccess(Uri uri) {
                if (mJSImageCallback != null && bWebViewFile == false) {
                    if(uri != null)
                        uploadImage(uri);
                    else {
                        WebJsBean bean = new WebJsBean();
                        bean.code = "CANCEL";
                        Gson gson = new Gson();
                        String sendData = gson.toJson(bean);
                        mJSImageCallback.callback(sendData);
                    }

                }
                else if(bWebViewFile == true){
                    if (mUploadMsg != null && uri != null) {

                        mUploadMsg.onReceiveValue(uri);
                        //mUploadMsg = null;
                    }
                    else if( mUploadFilesMsg != null && uri != null){
                        Uri[] results = new Uri[]{uri};
                        mUploadFilesMsg.onReceiveValue(results);
                        //mUploadFilesMsg = null;
                    }
                }
            }

            @Override
            public void onCancel() {
                if (mJSImageCallback != null) {

                    WebJsBean bean = new WebJsBean();
                    bean.code = "CANCEL";
                    Gson gson = new Gson();
                    String sendData = gson.toJson(bean);
                    mJSImageCallback.callback(sendData);
                }
            }

            @Override
            public void onFailed(String message) {
                if (mJSImageCallback != null) {

                    WebJsBean bean = new WebJsBean();
                    bean.code = "CANCEL";
                    Gson gson = new Gson();
                    String sendData = gson.toJson(bean);
                    mJSImageCallback.callback(sendData);
                }

            }
        });
        ImgPickHelper.getInstance().needCrop(false);

        if (bCamera) {
            String[] perms = {Manifest.permission.CAMERA};
            if (!EasyPermissions.hasPermissions(getActivity(), perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), CAMERA_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goCamera(getActivity());
            }

            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.CAMERA)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA}, CAMERA_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goCamera(getActivity());
            }*/

        } else {
            String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
            if (!EasyPermissions.hasPermissions(getActivity(), perms)) {
                EasyPermissions.requestPermissions(this, getString(R.string.file_permission_hint), WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE, perms);
            }else{
                ImgPickHelper.getInstance().goGallery(getActivity());
            }
            /*if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    Toast.makeText(getContext(), "please give me the permission", Toast.LENGTH_SHORT).show();
                } else {
                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
                }
            } else {
                ImgPickHelper.getInstance().goGallery(getActivity());
            }*/
        }
    }


    private void loadUrl(String url) {
        String webUrl = "";
        if(TextUtils.isEmpty(url)){
            webUrl = mUrl;
        }else{
            webUrl = url;
        }

        if (!webUrl.contains("channel=")) {
            if(webUrl.contains("?")){
                webUrl = webUrl + "&channel=" + CommonUtil.getChannel(getActivity());
            }else{
                webUrl = webUrl + "?channel=" + CommonUtil.getChannel(getActivity());
            }
        }
        webView.loadUrl(webUrl, setWebViewHeader());
    }

    public interface OnShowMainTabListener {
        void onShowMaintab(boolean show);
    }

    private OnShowMainTabListener mShowMainTabListener;

    public void SetShowMainTabListener(OnShowMainTabListener listener) {
        mShowMainTabListener = listener;
    }

    @Override
    protected void onVisibleChanged(boolean visible) {
        super.onVisibleChanged(visible);
        if (visible == true) {
            ResetUrl(mNewUrl);
        } else {
            if (mShowMainTabListener != null){
                mShowMainTabListener.onShowMaintab(true);
            }
        }
    }

    public void setNewUrl(String url) {
        mNewUrl = url;
    }

    private void ResetUrl(String url) {
        if (!TextUtils.isEmpty(url) && !url.equalsIgnoreCase(mUrl) && webView != null) {
            mUrl = url;
            DebugLog.e("WEB","LOAD:::   5");
            loadUrl(mUrl);
        }
    }


    private void initWebView() {
        WebSettings settings = webView.getSettings();

        //webView.setInitialScale(50);// 为25%，最小缩放等级
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//设置js可以直接打开窗口，如window.open()，默认为false
        settings.setJavaScriptEnabled(true);//是否允许执行js，默认为false。设置true时，会提醒可能造成XSS漏洞
        settings.setSupportZoom(true);//是否可以缩放，默认true
        settings.setBuiltInZoomControls(true);//是否显示缩放按钮，默认false
        settings.setUseWideViewPort(true);//设置此属性，可任意比例缩放。大视图模式
        settings.setDefaultTextEncodingName("UTF-8");
        settings.setLoadWithOverviewMode(true);//和setUseWideViewPort(true)一起解决网页自适应问题
        settings.setAppCacheEnabled(true);//是否使用缓存
        settings.setAllowFileAccess(true);
        settings.setDatabaseEnabled(true);
        //String dir = getActivity().getDir("database", Context.MODE_PRIVATE).getPath();
        //settings.setDatabasePath(dir);
        settings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = getActivity().getCacheDir().getAbsolutePath();
        settings.setAppCachePath(appCachePath);
        settings.setAppCacheEnabled(true);

        settings.setDomStorageEnabled(true);
        settings.setGeolocationEnabled(true);


        webView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                webView.requestFocus();
                return false;
            }
        });


        // 通过addJavascriptInterface()将Java对象映射到JS对象
        //参数1：Javascript对象名
        //参数2：Java对象名
        webView.addJavascriptInterface(new JsCallNative(new JsCallNative.JsCallback() {
            @Override
            public void Success(String token) {
//                ToastUtils.showShort("recaptcha验证："+token);
                Intent intent = new Intent();
                intent.putExtra("token", token);
                getActivity().setResult(RESULT_OK, intent);
                getActivity().finish();
            }

            @Override
            public void Failed(String failMsg) {
                ToastUtils.showShort(getActivity(), getResources().getString(R.string.string_verify_failed));
                ToastUtils.showShort(getActivity(), getResources().getString(R.string.string_verify_retry));
                webView.reload();

            }
        }), "app");//JsCallNative类对象映射到js的test对象

        MyWebChomeClient wvcc = new MyWebChomeClient(new MyWebChomeClient.OpenFileChooserCallBack() {
            @Override
            public void openFileChooserCallBack(ValueCallback<Uri> uploadMsg, String acceptType) {
                mUploadMsg = uploadMsg;
                showSelectPhoto(true);
                //Intent i  = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //i.addCategory(Intent.CATEGORY_OPENABLE);
                //i.setType("image/*");
                //getActivity().startActivityForResult(i, FILECHOOSER_RESULTCODE);
            }

            @Override
            public void openFilesChooserCallBack(ValueCallback<Uri[]> uploadMsg, String acceptType){
                mUploadFilesMsg = uploadMsg;
                showSelectPhoto(true);
                //Intent i  = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                //i.addCategory(Intent.CATEGORY_OPENABLE);
                //i.setType("image/*");
                //getActivity().startActivityForResult(i, FILECHOOSER_RESULTCODE);
            }

            @Override
            public void setWevTitle(String title) {
                if (!isSettedTitle) {
                    topBar.setTitle(title);
                }

            }

            @Override
            public void setProgress(int newProgress) {
                pb.setProgress(newProgress);
                if (newProgress >= 100) {
                    pb.setVisibility(View.GONE);
                }
            }

        });
        webView.setWebChromeClient(wvcc);

        /*webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                pb.setProgress(newProgress);
                if (newProgress >= 100) {
                    pb.setVisibility(View.GONE);
                }
            }
        });*/
    }


    private Map setWebViewHeader() {

        //设置与webviewheader
        Map extraHeaders = new HashMap();
        String lan = RateAndLocalManager.GetInstance(BHexApplication.getInstance()).getCurLocalLanguage();
        if (!lan.isEmpty()){
            extraHeaders.put(Fields.PARAM_LANGUAGE, lan);
        }
        //TODO-0205 公共参数，加入header,待测试
//        extraHeaders.put(Fields.PARAM_IMEI,DevicesUtil.getDeviceID(BHexApplication.getInstance()));
//        Map<String, String> deviceParams = DevicesUtil.getDeviceParams();
//        extraHeaders.putAll(deviceParams);

        String userAgent = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            userAgent = webView.getSettings().getDefaultUserAgent(getActivity());
        }

        String userAgentStr = DevicesUtil.getAppName(getActivity())+"/" + DevicesUtil.getAppVersionName(getActivity()) + " Android " + "lang/" + lan + " "
                + Build.VERSION.RELEASE + " " + userAgent;
        webView.getSettings().setUserAgentString(userAgentStr);

        SharedPrefsCookiePersistor cookiePersistor = new SharedPrefsCookiePersistor(CApplication.getInstance());
        List<Cookie> cookies = null;

        if (cookiePersistor != null){
            cookies = cookiePersistor.loadAll();
        }
        if (cookies != null && !cookies.isEmpty()) {
            CookieUtils.setCookies(getActivity(), cookies);
        }

        return extraHeaders;
    }

    class MyWebViewClient extends WVJBWebViewClient {
        public MyWebViewClient(final WebView webView) {

            // support js send
            super(webView, new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    //Toast.makeText(getActivity(), "ObjC Received message from JS:" + data, Toast.LENGTH_LONG).show();
                    callback.callback("Response for message from ObjC!");
                }
            });


            registerHandler("openFuture", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    //开通合约成功
                    getActivity().finish();
                }
            });


            registerHandler("appLanguage", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    WebJsBean bean = new WebJsBean();
                    bean.code = "OK";
                    //bean.data = new WebJsBean.JsData();
                    //bean.data.language = RateAndLocalManager.GetInstance(BHexApplication.getInstance()).getCurLocalLanguage();
                    callback.callback(bean);

                }
            });

            registerHandler("appGoPage", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsBean bean = gson.fromJson(data.toString(),
                                WebJsBean.class);
                        if (bean != null) {
                            if (bean.page.equalsIgnoreCase("login")) {
                                if (!UserInfo.isLogin()) {
                                    IntentUtils.goLogin(getActivity(), LOGIN_RESULTCODE, AppData.INTENT.LOGIN_CALLER_WEB);
//                                    Intent intent = new Intent();
//                                    intent.putExtra(AppData.INTENT.LOGIN_CALLER, AppData.INTENT.LOGIN_CALLER_WEB);
//                                    intent.setClass(getActivity(), LoginActivity.class);
//                                    getActivity().startActivityForResult(intent, LOGIN_RESULTCODE);
                                }
                            }

                        }
                    }
                }
            });

            registerHandler("login", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (isAlive()) {
                        if (!UserInfo.isLogin()) {
                            DebugLog.e("WEB","WEB::::  web--1");
                            IntentUtils.goLogin(getActivity(), LOGIN_RESULTCODE, AppData.INTENT.LOGIN_CALLER_WEB);
//                        Intent intent = new Intent();
//                        intent.putExtra(AppData.INTENT.LOGIN_CALLER, AppData.INTENT.LOGIN_CALLER_WEB);
//                        intent.setClass(getActivity(), LoginActivity.class);
//                        getActivity().startActivityForResult(intent, LOGIN_RESULTCODE);
                        } else{
                            loadUrl(webView.getUrl());
                            DebugLog.e("WEB","WEB::::  web--2");
                            DebugLog.e("WEB","LOAD:::   7");
                        }
                    }else{
                        DebugLog.e("WEB","WEB:::   is not alive");
                    }
                }
            });

            registerHandler("register", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (!UserInfo.isLogin()) {
                        IntentUtils.goRegister(getActivity(), LOGIN_RESULTCODE, AppData.INTENT.LOGIN_CALLER_WEB);
                    } else{
                        DebugLog.e("WEB","LOAD:::   8");
                        loadUrl(webView.getUrl());
                    }

                }
            });

            registerHandler("appSubmitPhoto", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsBean bean = gson.fromJson(data.toString(),
                                WebJsBean.class);
                    }
                    if (callback != null){
                        mJSImageCallback = callback;
                    }

                    //callback.callback("test");
                    showSelectPhoto(false);

                }
            });
            registerHandler("isFirstPage", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (data != null && bMainFragment == true) {
                        Gson gson = new Gson();
                        WebJsBean bean = gson.fromJson(data.toString(),
                                WebJsBean.class);
                        if(bean.isFirstPage == true){
                            showFirstPage();
                        }else{
                            showSecondPage(true);
                        }
                    }


                }
            });

            registerHandler("getShareData", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsBean bean = gson.fromJson(data.toString(),
                                WebJsBean.class);
                        ShareUtils.shareWeb(getActivity(), bean.link, bean.title, bean.desc);
                    }
                }
            });

            //分享图片
            registerHandler("getShareImg", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    String[] perms = {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE};
                    if (!EasyPermissions.hasPermissions(getActivity(), perms)) {
                        EasyPermissions.requestPermissions(getActivity(), getString(R.string.file_read_write_permission_hint), WRITE_EXTERNAL_STORAGE_SHARE_PERMISSION_REQUEST_CODE, perms);
                    } else {
                        if (data != null) {
                            Gson gson = new Gson();
                            String shareContent = data.toString();
                            DebugLog.e("SHARE",shareContent);
                            WebJsBean bean = gson.fromJson(shareContent,
                                    WebJsBean.class);
                            if (bean != null) {

                                shareImage(bean);

                            }
                        }
                    }

                }
            });

            registerHandler("browseImage", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsBean bean = gson.fromJson(data.toString(),
                                WebJsBean.class);
                        if(bean != null){
                            showPicBrowser(bean.currentImageIndex, bean.imageArray);
                        }
                    }
                }
            });

            //首页
            registerHandler("homePage", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    IntentUtils.goMain(getActivity());
                }
            });

            //行情列表
            registerHandler("quote", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    IntentUtils.goMarket(getActivity());
                }
            });

            //交易
            registerHandler("trade", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    Gson gson = new Gson();
                    if (data != null) {
                        WebJsTradeBean bean = gson.fromJson(data.toString(),
                                WebJsTradeBean.class);
                        if(bean != null){
                            String index_type = bean.index_type;
                            if (!TextUtils.isEmpty(index_type)) {
                                if (index_type.equals("coin")||index_type.equals("option") || index_type.equals("futures")) {
                                    String symbol_id = bean.symbol_id;
                                    if (!TextUtils.isEmpty(symbol_id)) {
                                        CoinPairBean coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(symbol_id);
                                        if (coinPairBean != null) {
                                            coinPairBean.setBuyMode(true);
                                            coinPairBean.setNeedSwitchTradeTab(true);
                                            IntentUtils.goMain(getActivity());
                                            EventBus.getDefault().postSticky(coinPairBean);
                                        }else{
                                            ToastUtils.showShort(getActivity().getResources().getString(R.string.string_data_exception));
                                        }
                                    }

                                }else if(index_type.equals("otc")){
                                    IntentUtils.goMain(getActivity());
                                    IntentUtils.goOTCTrade(MainActivity.getInstance());
                                }
                            }

                        }
                    }
                }
            });

            //查看K线
            registerHandler("symbolDetail", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsTradeBean bean = gson.fromJson(data.toString(),
                                WebJsTradeBean.class);
                        if(bean != null){
                            String symbol_id = bean.symbol_id;
                            if (!TextUtils.isEmpty(symbol_id)) {
                                CoinPairBean coinPairBean = SymbolDataManager.GetInstance().getSymbolInfoById(symbol_id);
                                if (coinPairBean != null) {
//                                    getActivity().finish();
                                    IntentUtils.goKline(getActivity(),coinPairBean);
                                }else{
                                    ToastUtils.showShort(getActivity().getResources().getString(R.string.string_data_exception));
                                }
                            }
                        }
                    }
                }
            });

            //查看资产  wallet:钱包 futures:合约 option:期权 bitmore:币多多
            registerHandler("assets", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsTradeBean bean = gson.fromJson(data.toString(),
                                WebJsTradeBean.class);
                        if(bean != null){
                            String indexType = bean.index_type;
                            if (!TextUtils.isEmpty(indexType)) {
                                if (indexType.equals("wallet")) {
                                    IntentUtils.goMyAsset(getActivity());
                                }else if(indexType.equals("option")){
                                    IntentUtils.goOptionAsset(getActivity());
                                }else if(indexType.equals("bitmore")){
                                    IntentUtils.goCoinPlusAsset();
                                }
                            }
                        }
                    }
                }
            });

            //实名认证 IDVerfication
            registerHandler("IDVerfication", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    if (UserInfo.isLogin(getActivity(), AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                        IntentUtils.goIdentityAuth(getActivity());
//                        UserInfoBean userInfo = UserInfo.getUserInfo();
//                        if (userInfo != null) {
//                            int verifyStatus = userInfo.getVerifyStatus();
//                            if (verifyStatus==VERIFY_STATUS.VERIFY_NO.getmStatus()) {
//                                IntentUtils.goIdentityAuth(getActivity());
//                                return;
//                            }else if(verifyStatus==VERIFY_STATUS.VERIFY_CHECK_FAILED.getmStatus()||verifyStatus==VERIFY_STATUS.VERIFY_CHECKING.getmStatus()){
//                                IntentUtils.goAuthStatus(getActivity(), null, verifyStatus,"");
//                                return;
//                            }
//                        }
//                        IntentUtils.goUserInfoPage(getActivity());
                    }
                }
            });

            //资产冲提币  index_type deposit:充币 withdraw:提币
            registerHandler("assetsAction", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {

                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsTradeBean bean = gson.fromJson(data.toString(),
                                WebJsTradeBean.class);
                        if(bean != null){
                            if (UserInfo.isLogin(getActivity(),"")) {
                                String indexType = bean.index_type;
                                String token_id = bean.token_id;
                                if (!TextUtils.isEmpty(indexType)) {
                                    if (TextUtils.isEmpty(token_id)) {
                                        ToastUtils.showShort("token_id is not allow empty");
                                        return;
                                    }
                                    if (indexType.equals("deposit")) {
                                        //充币
                                        IntentUtils.goMyAssetTokenDeposit(token_id,getActivity());
                                    }else if(indexType.equals("withdraw")){
                                        //提币
                                        IntentUtils.goMyAssetTokenWithdraw(token_id,getActivity());
                                    }else{
                                        ToastUtils.showShort("call illegal");
                                    }
                                }
                            }
                        }
                    }
                }
            });

            //我的
            registerHandler("me", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    IntentUtils.goAccount(getActivity());
                }
            });

            //我的邀请
            registerHandler("myInvitation", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    if (UserInfo.isLogin(getActivity(),AppData.INTENT.LOGIN_CALLER_TAB_ACCOUNT)) {
                        IntentUtils.goMyInvitation(getActivity());
                    }
                }
            });

            //帮助中心
            registerHandler("guide", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    UiConfig helpCenterConfig = HelpCenterActivity.builder()
                            //.withContactUsButtonVisible(true)
                            //.withArticlesForCategoryIds(360000882773L)
                            .config();

                    HelpCenterActivity.builder()
                            //.withLabelNames("Announcements")
                            .show(getContext(), helpCenterConfig );

                }
            });

            //客服
            registerHandler("help", new WVJBWebViewClient.WVJBHandler() {

                @Override
                public void request(Object data, WVJBResponseCallback callback) {
                    IntentUtils.goZendeskChat(getActivity());
                }
            });

        }

/*        public void getShareData() {
            callHandler("getShareData", null, new WVJBResponseCallback() {

                @Override
                public void callback(Object data) {
                    if (data != null) {
                        Gson gson = new Gson();
                        WebJsBean bean = gson.fromJson(data.toString(),
                                WebJsBean.class);
                        if (bean != null) {

                        }
                    }
                }
            });
        }*/

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            if (TextUtils.isEmpty(url)) return true;

            for (String scheme : INCLUDE_SCHEME_ARRAY) {
                if (url.startsWith(scheme)) {
                    return super.shouldOverrideUrlLoading(view, url);
                }

            }

            try {

                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                startActivity(intent);

            } catch (Exception e) {
            }


            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mBnetworkError = false;
            pb.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            int pageSize = webView.copyBackForwardList().getCurrentIndex();
            if (bMainFragment == true) {
                if (pageSize > 0) {
                    showSecondPage(false);
                }
            }
            else {
                if (pageSize > 0) {
                    topBar.findViewById(R.id.title_bar_left_text).setVisibility(View.VISIBLE);
                }else{
                    topBar.findViewById(R.id.title_bar_left_text).setVisibility(View.GONE);
                }
            }
            pb.setVisibility(View.GONE);
            super.onPageFinished(view, url);
            if (!isSettedTitle) {
                topBar.setTitle(view.getTitle());
            }
            if (!mBnetworkError) {
                ll_network_error.setVisibility(View.GONE);
                webView.setVisibility(View.VISIBLE);
            } else {
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        ll_network_error.setVisibility(View.VISIBLE);
                        webView.setVisibility(View.GONE);
                    }
                }, 500);
            }
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,
                                    String description, String failingUrl) {
            super.onReceivedError(view, errorCode, description, failingUrl);
            mBnetworkError = true;
            ll_network_error.setVisibility(View.VISIBLE);
            webView.setVisibility(View.GONE);
        }

        @Override
        public void onReceivedSslError(WebView view, final SslErrorHandler handler,
                                       SslError error) {
            if (handler != null) {
//                handler.proceed(); // 接受所有网站的证书
                //TODO 证书check待处理
                DialogUtils.showDialog(getActivity(), getString(R.string.string_reminder), getString(R.string.string_access_webpage_risk_tips), getString(R.string.string_continue_open),getString(R.string.string_close_page), false, new DialogUtils.OnButtonEventListener() {
                    //            DialogUtils.showDialog(getActivity(), getString(R.string.string_reminder), getString(R.string.string_pinning_tips), getString(R.string.string_sure),getString(R.string.string_close_page), false, new DialogUtils.OnButtonEventListener() {
                    @Override
                    public void onConfirm() {
                        handler.proceed();
                    }

                    @Override
                    public void onCancel() {
                        handler.cancel();
                        getActivity().finish();
                    }
                });
            }

        }

        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }


        @Override
        public void onReceivedClientCertRequest(WebView view, ClientCertRequest request) {
            super.onReceivedClientCertRequest(view, request);
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView view, HttpAuthHandler handler, String host, String realm) {
            super.onReceivedHttpAuthRequest(view, handler, host, realm);
        }
    }

    private void shareImage(final WebJsBean bean) {
        try{
            if (bean != null) {
                Observable.create(new ObservableOnSubscribe<Bitmap>() {

                    @Override
                    public void subscribe(ObservableEmitter<Bitmap> emitter) throws Exception {
                        String imgUrl = bean.imgUrl;//base64

                        if (!TextUtils.isEmpty(imgUrl)) {
                            byte[] qrCodeByte = Base64.decode(imgUrl, Base64.DECODE);
                            Bitmap bitmap = BitmapUtils.Bytes2Bimap(qrCodeByte);

                            emitter.onNext(bitmap);
                            emitter.onComplete();
                        }
                    }
                }).subscribeOn(Schedulers.computation())
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Observer<Bitmap>() {
                            @Override
                            public void onSubscribe(Disposable d) {
                                getUI().showProgressDialog("","");
                            }

                            @Override
                            public void onNext(Bitmap bitmap) {
                                String resultPath = BitmapUtils.saveBitmap(getActivity(),bitmap);
                                DebugLog.e("SHARE",resultPath);
//                                SystemShareUtils.shareImage(getActivity(),resultPath);
                                showShare(resultPath,bitmap);
                            }

                            @Override
                            public void onError(Throwable e) {

                            }

                            @Override
                            public void onComplete() {
                                getUI().dismissProgressDialog();
                            }
                        });

            }
        }catch (Exception e){

        }
    }

    private void showShare(final String resultPath, final Bitmap resultBitmap) {
        DialogUtils.showShareDialogOneBtn(getActivity(), "", resultPath, true,new DialogUtils.OnShareListener() {
            @Override
            public void onShareWx() {
                ShareUtils.share(SHARE_MEDIA.WEIXIN, resultBitmap);

            }

            @Override
            public void onShareWxCircle() {
                ShareUtils.share(SHARE_MEDIA.WEIXIN_CIRCLE, resultBitmap);
            }

            @Override
            public void onSavePic() {
                ImageUtils.saveImageToGallery(getActivity(), resultBitmap);

                ToastUtils.showShort(getString(R.string.string_save_success));
            }

            @Override
            public void onMore() {
                SystemShareUtils.shareImage(getActivity(),resultPath);
            }

            @Override
            public void onCancel() {

            }
        });

    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        ImgPickHelper.getInstance().handleResult(getActivity(), requestCode, resultCode, data);

        /*if ((requestCode == 126 || requestCode == 128) && resultCode == RESULT_OK) {
            if (mUploadMsg != null && data != null) {

                mUploadMsg.onReceiveValue(data.getData());
                mUploadMsg = null;
            }
            else if( mUploadFilesMsg != null && data != null){
                Uri[] results = new Uri[]{data.getData()};;
                mUploadFilesMsg.onReceiveValue(results);
                mUploadFilesMsg = null;
            }

        }*/
        if (requestCode == LOGIN_RESULTCODE && resultCode == RESULT_OK) {
            DebugLog.e("WEB","LOAD:::   6");
            loadUrl(webView.getUrl());
        }
//        UMShareAPI.get(getActivity()).onActivityResult(requestCode, resultCode, data);
    }

    private void uploadImage(Uri fromUri) {

        if (FileTools.fileIsExists(fromUri.getPath())) {

            UtilsApi.UploadGuildImg(fromUri.getPath(), new SimpleResponseListener<UploadImgResponse>() {

                @Override
                public void onSuccess(UploadImgResponse response) {
                    super.onSuccess(response);
                    if (CodeUtils.isSuccess(response, false)) {

                        //ToastUtils.showShort(getActivity(), response.getUrl());
                        if (mJSImageCallback != null) {
                            WebJsBean bean = new WebJsBean();
                            bean.code = "OK";
                            List<String> urls = new ArrayList<>();
                            urls.add(response.getUrl());
                            bean.data  = response.array;
                            Gson gson = new Gson();
                            String sendData = gson.toJson(bean);
                            mJSImageCallback.callback(sendData);
                            //FileTools.deleteFile(IMAGE_TEMP_PATH);
                            ImgPickHelper.getInstance().clearCachedCropFile(getContext());
                        }

                    } else if (mJSImageCallback != null) {
                        WebJsBean bean = new WebJsBean();
                        bean.code = "ERROR";
                        Gson gson = new Gson();
                        String sendData = gson.toJson(bean);
                        mJSImageCallback.callback(sendData);
                    }
                }

                @Override
                public void onError(Throwable error) {
                    if (mJSImageCallback != null) {
                        WebJsBean bean = new WebJsBean();
                        bean.code = "ERROR";
                        Gson gson = new Gson();
                        String sendData = gson.toJson(bean);
                        mJSImageCallback.callback(sendData);
                    }
                }

            });
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }
    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
//        requestCodeQRCodePermissions();
    }
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE){
            //takingPicture();
            ImgPickHelper.getInstance().goCamera(getActivity());
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
            //mSourceIntent = ImageUtils.choosePicture();
            //startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
            ImgPickHelper.getInstance().goGallery(getActivity());
        } else {
            //Toast.makeText(getActivity(), "request permission fail!", Toast.LENGTH_SHORT).show();
        }
    }

/*    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //takingPicture();
            ImgPickHelper.getInstance().goCamera(getActivity());
        } else if (requestCode == WRITE_EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //mSourceIntent = ImageUtils.choosePicture();
            //startActivityForResult(mSourceIntent, FILECHOOSER_RESULTCODE);
            ImgPickHelper.getInstance().goGallery(getActivity());
        } else {
            Toast.makeText(getActivity(), "request camara permission fail!", Toast.LENGTH_SHORT).show();
        }
    }*/


    @Override
    public void onDestroy() {
        super.onDestroy();
//        UMShareAPI.get(getActivity()).release();
        ImgPickHelper.getInstance().unregistHandler();
    }

    /**
     *预览图片
     */
    private void showPicBrowser(int index, List<String> imgUrls) {

        if(imgUrls == null || index >= imgUrls.size())
            return;

        ArrayList<ImageInfo> imageInfoList = new ArrayList<>();
        ImageInfo imageInfo;
        for (String imgUrl : imgUrls) {
            imageInfo = new ImageInfo();
            // 原图地址（必填）
            imageInfo.setOriginUrl(imgUrl);
            // 缩略图地址（必填）
            // 如果没有缩略图url，可以将两项设置为一样。（注意：此处作为演示用，加了-1200，你们不要这么做）
//            imageInfo.setThumbnailUrl(image.concat("-1200"));
            imageInfo.setThumbnailUrl(imgUrl);
            imageInfoList.add(imageInfo);
            imageInfo = null;
        }

        ImagePreview.getInstance()
                .setContext(getActivity())
                .setIndex(index)
                .setImageInfoList(imageInfoList)
                .setShowDownButton(true)
                //.setLoadStrategy(ImagePreview.LoadStrategy.NetworkAuto)
                .setFolderName("BhexImage")
                .setScaleLevel(1, 3, 5)
                .setZoomTransitionDuration(300)

                .setEnableClickClose(true)// 是否启用点击图片关闭。默认启用
                .setEnableDragClose(true)// 是否启用上拉/下拉关闭。默认不启用

                .setShowCloseButton(true)// 是否显示关闭页面按钮，在页面左下角。默认不显示
                .setCloseIconResId(R.drawable.ic_action_close)// 设置关闭按钮图片资源，可不填，默认为：R.drawable.ic_action_close

                .setShowDownButton(true)// 是否显示下载按钮，在页面右下角。默认显示
                .setDownIconResId(R.drawable.icon_download_new)// 设置下载按钮图片资源，可不填，默认为：R.drawable.icon_download_new

                .setShowIndicator(true)// 设置是否显示顶部的指示器（1/9）。默认显示
                .start();
    }

}
